All files / services WhatsAppService.js

0% Statements 0/470
0% Branches 0/251
0% Functions 0/46
0% Lines 0/450

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * WhatsAppService.js
 * 
 * Multi-tenant WhatsApp service manager
 * Manages separate WhatsApp connections for each tenant
 * Based on Baileys 6.5.0
 * 
 * @module services/WhatsAppService
 */
 
const path = require('path');
const fs = require('fs').promises;
const { logger } = require('../config/logger');
const { pool } = require('../config/database');
const BillingService = require('./BillingService');
 
// WhatsApp modules (will be loaded per tenant)
const WhatsAppConnection = require('./whatsapp/WhatsAppConnection');
const WhatsAppMessageHandler = require('./whatsapp/WhatsAppMessageHandler');
const WhatsAppMediaHandler = require('./whatsapp/WhatsAppMediaHandler');
const WhatsAppQRHandler = require('./whatsapp/WhatsAppQRHandler');
const WhatsAppStateManager = require('./whatsapp/WhatsAppStateManager');
 
/**
 * Multi-tenant WhatsApp Service
 * Manages separate WhatsApp instances for each tenant
 */
class WhatsAppService {
  constructor(io) {
    this.io = io;
    this.tenantInstances = new Map(); // tenantId => WhatsAppInstance
    this.sessionsPath = path.join(__dirname, '../sessions');
    this.uploadsPath = path.join(__dirname, '../uploads');
    this.rateLimits = new Map(); // key: `${tenantId}:${phone}` -> { lastSentAt, windowStart, windowCount }
  }
 
  /**
   * Initialize WhatsApp service for a tenant
   * @param {number} tenantId - Tenant ID
   * @param {Object} options - Configuration options
   * @returns {Promise<Object>} Instance details
   */
  async initializeTenant(tenantId, options = {}) {
    try {
      // Check if tenant already has an instance
      if (this.tenantInstances.has(tenantId)) {
        const existingInstance = this.tenantInstances.get(tenantId);
        const isConnected = existingInstance.connection.isConnected(tenantId);
        
        logger.info(`Tenant ${tenantId} already has WhatsApp instance`, { isConnected });
        
        // If already connected, return the instance
        if (isConnected) {
          return existingInstance;
        }
        
        // If not connected, try to initialize again
        logger.info(`Tenant ${tenantId} instance exists but not connected, reinitializing...`);
        const tenantState = existingInstance.connection.getTenantState(tenantId);
        const eventHandlers = tenantState ? tenantState.eventHandlers : {};
        await existingInstance.connection.initialize(tenantId, eventHandlers);
        
        return existingInstance;
      }
 
      let tenant;
      
      // Special case: tenant 0 is superadmin (system notifications)
      if (tenantId === 0) {
        tenant = {
          id: 0,
          name: 'Superadmin',
          subdomain: 'superadmin',
          status: 'active'
        };
        logger.info('Initializing WhatsApp for superadmin notifications (tenant 0)');
      } else {
        // Verify tenant exists and is active
        const connection = await pool.getConnection();
        const [tenants] = await connection.query(
          'SELECT * FROM tenants WHERE id = ? AND status = ?',
          [tenantId, 'active']
        );
        connection.release();
 
        if (!tenants.length) {
          throw new Error('Tenant not found or inactive');
        }
 
        tenant = tenants[0];
      }
 
      // Create tenant-specific paths
      const tenantSessionPath = path.join(this.sessionsPath, `tenant_${tenantId}`);
      const tenantUploadPath = path.join(this.uploadsPath, `tenant_${tenantId}`);
 
      // Ensure directories exist (parallel for speed)
      await Promise.all([
        fs.mkdir(tenantSessionPath, { recursive: true }),
        fs.mkdir(tenantUploadPath, { recursive: true })
      ]);
 
      // Create tenant-specific Socket.IO namespace
      const tenantNamespace = this.io.of(`/tenant/${tenantId}`);
 
      // Initialize WhatsApp modules for this tenant
      const stateManager = new WhatsAppStateManager(tenantSessionPath);
      const qrHandler = new WhatsAppQRHandler(tenantNamespace, {
        maxQrGenerations: 3,
        qrTimeoutDuration: 60000
      });
      const mediaHandler = new WhatsAppMediaHandler({
        uploadPath: tenantUploadPath,
        maxFileSize: 50 * 1024 * 1024
      });
      const whatsappConnection = new WhatsAppConnection(
        tenantNamespace,
        stateManager,
        qrHandler,
        { maxReconnectAttempts: 5 }
      );
      // CRITICAL FIX: Pass main io object, not namespace
      const messageHandler = new WhatsAppMessageHandler(
        this.io,
        mediaHandler,
        { enableOpenAI: options.enableOpenAI || false, tenantId }
      );
 
      // Create instance object
      const instance = {
        tenantId,
        tenant,
        connection: whatsappConnection,
        messageHandler,
        mediaHandler,
        qrHandler,
        stateManager,
        namespace: tenantNamespace,
        isConnected: false,
        createdAt: new Date()
      };
 
      // Setup message handler
      const onMessageHandler = async (m) => {
        try {
          // Check usage limits before processing
          const withinLimits = await BillingService.checkUsageLimits(tenantId);
          
          if (!withinLimits) {
            logger.warn(`Tenant ${tenantId} exceeded usage limits`);
            tenantNamespace.emit('usage-limit-exceeded', {
              message: 'Monthly message limit exceeded'
            });
            return;
          }
 
          const sock = whatsappConnection.getSocket(tenantId);
          const downloadMediaMessage = whatsappConnection.getDownloadMediaMessage();
          
          console.log(`📞 [WhatsAppService] Calling messageHandler.handleMessage for tenant ${tenantId}`);
          await messageHandler.handleMessage(tenantId, m, sock, downloadMediaMessage);
          
          // Track usage
          await BillingService.trackMessageUsage(tenantId, 1);
        } catch (error) {
          logger.error(`Error handling message for tenant ${tenantId}:`, error);
        }
      };
 
      // Initialize connection - PASS tenantId as first parameter
      await whatsappConnection.initialize(tenantId, {
        onMessage: onMessageHandler
      });
 
      // Store instance
      this.tenantInstances.set(tenantId, instance);
 
      logger.info(`WhatsApp initialized for tenant ${tenantId}`);
 
      return instance;
    } catch (error) {
      logger.error(`Error initializing WhatsApp for tenant ${tenantId}:`, error);
      throw error;
    }
  }
 
  /**
   * Get WhatsApp instance for a tenant
   * @param {number} tenantId - Tenant ID
   * @returns {Object|null} WhatsApp instance
   */
  getInstance(tenantId) {
    return this.tenantInstances.get(tenantId) || null;
  }
 
  /**
   * Send message for a tenant
   * @param {number} tenantId - Tenant ID
   * @param {string} phoneNumber - Recipient phone number
   * @param {string} messageText - Message text
   * @param {number} conversationId - Conversation ID (optional)
   * @returns {Promise<Object>} Send result
   */
  async sendMessage(tenantId, phoneNumber, messageText, conversationId = null) {
    try {
      logger.info(`[WhatsAppService.sendMessage] Called`, { tenantId, phoneNumber, messageLength: messageText.length });
      
      // Check usage limits
      const withinLimits = await BillingService.checkUsageLimits(tenantId);
      
      logger.info(`[WhatsAppService.sendMessage] Usage limits check`, { tenantId, withinLimits });
      
      if (!withinLimits) {
        return {
          success: false,
          error: 'Monthly message limit exceeded'
        };
      }
 
      const instance = this.getInstance(tenantId);
      
      logger.info(`[WhatsAppService.sendMessage] Instance check`, { tenantId, hasInstance: !!instance });
      
      if (!instance) {
        return {
          success: false,
          error: 'WhatsApp not initialized for this tenant'
        };
      }
 
      const sock = instance.connection.getSocket(tenantId);
      const isConnected = instance.connection.isConnected(tenantId);
      
      logger.info(`[WhatsAppService.sendMessage] Connection check`, { 
        tenantId, 
        hasSock: !!sock, 
        isConnected,
        sockUser: sock?.user?.id,
        sockAuthState: sock?.authState?.creds?.me?.id
      });
      
      if (!sock || !isConnected) {
        try {
          logger.info(`[WhatsAppService.sendMessage] Attempting reconnect`, { tenantId });
          await instance.connection.reconnect(tenantId);
          const wait = async (ms) => new Promise(r => setTimeout(r, ms));
          await wait(1500);
        } catch (reconnectError) {
          logger.warn(`[WhatsAppService.sendMessage] Reconnect attempt failed`, { tenantId, error: reconnectError.message });
        }
        const sockAfter = instance.connection.getSocket(tenantId);
        const connectedAfter = instance.connection.isConnected(tenantId);
        if (!sockAfter || !connectedAfter) {
          return {
            success: false,
            error: 'WhatsApp not connected'
          };
        }
      }
 
      // Anti-ban: strict per-contact rate limit and human-like jitter
      const local = phoneNumber.includes('@') ? phoneNumber.split('@')[0] : phoneNumber.replace(/^\+/, '');
      const rateKey = `${tenantId}:${local}`;
      const now = Date.now();
      const minIntervalMs = 4000;       // min 4s between messages to same contact
      const windowMs = 60000;           // 1 minute window
      const limitPerWindow = 15;        // max 15 messages per minute to same contact
      const state = this.rateLimits.get(rateKey) || { lastSentAt: 0, windowStart: now, windowCount: 0 };
      const inWindow = now - state.windowStart < windowMs;
      const countOk = inWindow ? state.windowCount < limitPerWindow : true;
      const intervalOk = now - state.lastSentAt >= minIntervalMs;
      if (!countOk || !intervalOk) {
        const retryAfterMs = intervalOk ? (state.windowStart + windowMs - now) : (minIntervalMs - (now - state.lastSentAt));
        logger.warn(`[WhatsAppService.sendMessage] Rate limited`, { tenantId, local, retryAfterMs });
        return { success: false, error: 'Rate limited. Retry later.' };
      }
      // Update rate state pre-send to serialize multiple sends
      if (!inWindow) {
        state.windowStart = now;
        state.windowCount = 0;
      }
      state.lastSentAt = now;
      state.windowCount += 1;
      this.rateLimits.set(rateKey, state);
      // Human-like jitter
      const jitterMs = 800 + Math.floor(Math.random() * 1400);
      await new Promise(r => setTimeout(r, jitterMs));
 
      // If phoneNumber already contains @, use it as JID directly (it's a remoteJid)
      // Otherwise, format it as a WhatsApp JID
      // CRITICAL FIX: Handle @lid format - WhatsApp may need @s.whatsapp.net for sending
      let jid;
      if (phoneNumber.includes('@')) {
        const local = phoneNumber.split('@')[0];
        if (phoneNumber.includes('@lid')) {
          jid = `${local}@s.whatsapp.net`;
        } else {
          jid = phoneNumber;
        }
        logger.info(`[WhatsAppService.sendMessage] Using JID format`, { 
          tenantId, 
          originalPhone: phoneNumber, 
          jid,
          isLid: phoneNumber.includes('@lid'),
          isWhatsappNet: phoneNumber.includes('@s.whatsapp.net')
        });
      } else {
        const cleanPhone = phoneNumber.replace(/^\+/, '');
        jid = `${cleanPhone}@s.whatsapp.net`;
      }
      
      logger.info(`[WhatsAppService.sendMessage] Sending to JID`, { 
        tenantId, 
        originalPhone: phoneNumber, 
        jid,
        messageLength: messageText.length
      });
      
      let sentMessageResult;
      try {
        // CRITICAL FIX: Try without timeout first to see if it completes
        logger.info(`[WhatsAppService.sendMessage] Calling sock.sendMessage...`, { tenantId, jid });
        
        sentMessageResult = await sock.sendMessage(jid, { text: messageText });
        
        logger.info(`[WhatsAppService.sendMessage] sock.sendMessage completed`, { 
          tenantId, 
          jid,
          result: sentMessageResult ? 'success' : 'no result',
          messageId: sentMessageResult?.key?.id
        });
      } catch (sendError) {
        logger.error(`[WhatsAppService.sendMessage] sock.sendMessage failed`, { 
          tenantId, 
          jid, 
          error: sendError.message,
          errorCode: sendError.code,
          stack: sendError.stack 
        });
        return {
          success: false,
          error: `Failed to send WhatsApp message: ${sendError.message}`
        };
      }
      
      logger.info(`[WhatsAppService.sendMessage] Message sent successfully`, { tenantId, jid });
      
      // Save outgoing message with WhatsApp message ID for edit/delete support
      if (conversationId) {
        await instance.messageHandler.saveOutgoingMessage(
          tenantId,
          phoneNumber.replace('@s.whatsapp.net', '').replace('@lid', ''),
          messageText,
          {
            messageType: 'text',
            conversationId: conversationId,
            whatsappMessageId: sentMessageResult?.key?.id || null
          }
        );
      }
 
      // Track usage
      await BillingService.trackMessageUsage(tenantId, 1);
      
      logger.info(`Message sent for tenant ${tenantId} to ${phoneNumber}`);
      
      // CRITICAL FIX: Emit real-time update to tenant namespace
      const tenantNamespace = this.io.of(`/tenant/${tenantId}`);
      tenantNamespace.emit('message-sent', {
        conversationId: conversationId,
        phoneNumber: phoneNumber.replace('@s.whatsapp.net', '').replace('@lid', ''),
        message: messageText,
        timestamp: new Date()
      });
      
      // Return success with WhatsApp message ID for edit/delete support
      return { 
        success: true,
        whatsappMessageId: sentMessageResult?.key?.id || null
      };
    } catch (error) {
      logger.error(`[WhatsAppService.sendMessage] Error sending message for tenant ${tenantId}:`, error);
      return { success: false, error: error.message };
    }
  }
 
  /**
   * Send media message for a tenant
   * @param {number} tenantId - Tenant ID
   * @param {string} phoneNumber - Recipient phone number
   * @param {string} filePathOrUrl - Media file path or URL (can be /uploads/filename or full path)
   * @param {string} caption - Media caption
   * @param {number} conversationId - Conversation ID (optional)
   * @returns {Promise<Object>} Send result
   */
  async sendMediaMessage(tenantId, phoneNumber, filePathOrUrl, caption = '', conversationId = null) {
    try {
      logger.info(`[sendMediaMessage] Starting for tenant ${tenantId}`, { phoneNumber, filePathOrUrl, caption });
      
      // Check usage limits
      const withinLimits = await BillingService.checkUsageLimits(tenantId);
      
      if (!withinLimits) {
        return {
          success: false,
          error: 'Monthly message limit exceeded'
        };
      }
 
      const instance = this.getInstance(tenantId);
      
      if (!instance) {
        return {
          success: false,
          error: 'WhatsApp not initialized for this tenant'
        };
      }
 
      const sock = instance.connection.getSocket(tenantId);
      
      if (!sock || !instance.connection.isConnected(tenantId)) {
        return {
          success: false,
          error: 'WhatsApp not connected'
        };
      }
 
      // Anti-ban: rate-limit and jitter for media too
      const local = phoneNumber.includes('@') ? phoneNumber.split('@')[0] : phoneNumber.replace(/^\+/, '');
      const rateKey = `${tenantId}:${local}`;
      const now = Date.now();
      const minIntervalMs = 5000;       // stricter interval for media
      const windowMs = 60000;
      const limitPerWindow = 10;        // lower limit for media
      const state = this.rateLimits.get(rateKey) || { lastSentAt: 0, windowStart: now, windowCount: 0 };
      const inWindow = now - state.windowStart < windowMs;
      const countOk = inWindow ? state.windowCount < limitPerWindow : true;
      const intervalOk = now - state.lastSentAt >= minIntervalMs;
      if (!countOk || !intervalOk) {
        const retryAfterMs = intervalOk ? (state.windowStart + windowMs - now) : (minIntervalMs - (now - state.lastSentAt));
        logger.warn(`[WhatsAppService.sendMediaMessage] Rate limited`, { tenantId, local, retryAfterMs });
        return { success: false, error: 'Rate limited. Retry later.' };
      }
      if (!inWindow) {
        state.windowStart = now;
        state.windowCount = 0;
      }
      state.lastSentAt = now;
      state.windowCount += 1;
      this.rateLimits.set(rateKey, state);
      const jitterMs = 1200 + Math.floor(Math.random() * 1800);
      await new Promise(r => setTimeout(r, jitterMs));
 
      // CRITICAL FIX: Convert URL path to actual file path
      let actualFilePath = filePathOrUrl;
      
      // If it's a URL path like /uploads/filename, convert to actual file path
      if (filePathOrUrl.startsWith('/uploads/')) {
        actualFilePath = path.join(__dirname, '..', filePathOrUrl);
        logger.info(`[sendMediaMessage] Converted URL to path: ${actualFilePath}`);
      } else if (!path.isAbsolute(filePathOrUrl)) {
        // If it's a relative path, make it absolute from project root
        actualFilePath = path.join(__dirname, '..', filePathOrUrl);
        logger.info(`[sendMediaMessage] Made path absolute: ${actualFilePath}`);
      }
 
      // Check if file exists
      const fsSync = require('fs');
      if (!fsSync.existsSync(actualFilePath)) {
        logger.error(`[sendMediaMessage] File not found: ${actualFilePath}`);
        return { success: false, error: `File not found: ${actualFilePath}` };
      }
 
      const media = await instance.mediaHandler.uploadMedia(tenantId, actualFilePath);
      
      if (!media) {
        logger.error(`[sendMediaMessage] Error uploading media for tenant ${tenantId}`);
        return { success: false, error: 'Error uploading media' };
      }
 
      const jid = phoneNumber.includes('@') ? phoneNumber : `${phoneNumber}@s.whatsapp.net`;
      
      // CRITICAL FIX: Build message with proper mimetype and filename for documents
      const message = {};
      
      // Get original filename for documents
      const originalFilename = path.basename(actualFilePath);
 
      if (media.messageType === 'image') {
        message.image = media.buffer;
        message.mimetype = media.mimeType;
        if (caption) message.caption = caption;
      } else if (media.messageType === 'video') {
        message.video = media.buffer;
        message.mimetype = media.mimeType;
        if (caption) message.caption = caption;
      } else if (media.messageType === 'audio') {
        message.audio = media.buffer;
        message.mimetype = media.mimeType;
        // Voice note (ptt) for ogg, webm, or mp4 audio
        message.ptt = media.mimeType.includes('ogg') || 
                      media.mimeType.includes('webm') || 
                      media.mimeType.includes('opus');
      } else {
        // Document - CRITICAL: Include mimetype and filename
        message.document = media.buffer;
        message.mimetype = media.mimeType;
        message.fileName = originalFilename;
        if (caption) message.caption = caption;
      }
      
      logger.info(`[sendMediaMessage] Sending ${media.messageType} with mimetype: ${media.mimeType}, filename: ${originalFilename}`);
 
      const sentMediaResult = await sock.sendMessage(jid, message);
      
      // Save outgoing message with WhatsApp message ID for edit/delete support
      if (conversationId) {
        await instance.messageHandler.saveOutgoingMessage(
          tenantId,
          phoneNumber.replace('@s.whatsapp.net', '').replace('@lid', ''),
          caption || '[Media]',
          {
            messageType: media.messageType,
            mediaUrl: filePathOrUrl,
            conversationId: conversationId,
            whatsappMessageId: sentMediaResult?.key?.id || null
          }
        );
      }
      
      // Track usage
      await BillingService.trackMessageUsage(tenantId, 1);
      
      // Emit real-time update
      const tenantNamespace = this.io.of(`/tenant/${tenantId}`);
      tenantNamespace.emit('message-sent', {
        conversationId: conversationId,
        phoneNumber: phoneNumber.replace('@s.whatsapp.net', '').replace('@lid', ''),
        message: caption || '[Media]',
        mediaUrl: filePathOrUrl,
        mediaType: media.messageType,
        timestamp: new Date()
      });
      
      logger.info(`Media message sent for tenant ${tenantId}`);
      
      // Return success with WhatsApp message ID for edit/delete support
      return { 
        success: true,
        whatsappMessageId: sentMediaResult?.key?.id || null
      };
    } catch (error) {
      logger.error(`Error sending media for tenant ${tenantId}:`, error);
      return { success: false, error: error.message };
    }
  }
 
  /**
   * Get connection status for a tenant
   * @param {number} tenantId - Tenant ID
   * @returns {Object} Connection status
   */
  getStatus(tenantId) {
    const instance = this.getInstance(tenantId);
    
    if (!instance) {
      return {
        connected: false,
        initialized: false,
        error: 'Not initialized'
      };
    }
 
    const connStatus = instance.connection.getStatus(tenantId);
    const sessionInfo = instance.stateManager.getSessionInfo(tenantId);
    
    return {
      ...connStatus,
      session: sessionInfo,
      phoneNumber: this.getPhoneNumber(tenantId),
      initialized: true
    };
  }
 
  /**
   * Get connected phone number for a tenant
   * @param {number} tenantId - Tenant ID
   * @returns {string|null} Phone number
   */
  getPhoneNumber(tenantId) {
    try {
      const instance = this.getInstance(tenantId);
      
      if (!instance) return null;
      
      const sock = instance.connection.getSocket(tenantId);
      
      if (!sock || !instance.connection.isConnected(tenantId)) {
        return null;
      }
      
      const user = sock.user;
      return user?.id ? user.id.split(':')[0] : null;
    } catch (error) {
      return null;
    }
  }
 
  async getWebConversations(tenantId) {
    try {
      const normalizedTenantId = Number(tenantId);
      logger.info('Web conversations fetch start', { tenantId: normalizedTenantId });
      let instance = this.getInstance(normalizedTenantId);
      if (!instance) {
        await this.initializeTenant(normalizedTenantId);
        instance = this.getInstance(normalizedTenantId);
      } else if (!instance.connection.isConnected(normalizedTenantId)) {
        await this.initializeTenant(normalizedTenantId);
      }
 
      if (!instance) {
        return [];
      }
 
      const waitFor = async (condition, timeoutMs, intervalMs) => {
        const start = Date.now();
        while (Date.now() - start < timeoutMs) {
          if (await condition()) return true;
          await new Promise(resolve => setTimeout(resolve, intervalMs));
        }
        return false;
      };
 
      if (!instance.connection.isConnected(normalizedTenantId)) {
        await waitFor(() => instance.connection.isConnected(normalizedTenantId), 10000, 500);
      }
 
      let chats = await instance.connection.getChats(normalizedTenantId);
      if (!chats.length && instance.connection.isConnected(normalizedTenantId)) {
        await instance.connection.forceHistorySync(normalizedTenantId);
        await waitFor(async () => {
          const nextChats = await instance.connection.getChats(normalizedTenantId);
          if (nextChats.length) {
            chats = nextChats;
            return true;
          }
          return false;
        }, 30000, 1000);
      }
      if (!chats.length && instance.connection.isConnected(normalizedTenantId)) {
        await instance.connection.reconnect(normalizedTenantId);
        await waitFor(() => instance.connection.isConnected(normalizedTenantId), 15000, 500);
        await waitFor(async () => {
          const nextChats = await instance.connection.getChats(normalizedTenantId);
          if (nextChats.length) {
            chats = nextChats;
            return true;
          }
          return false;
        }, 20000, 1000);
      }
      logger.info('Web conversations fetch result', {
        tenantId: normalizedTenantId,
        connected: instance.connection.isConnected(normalizedTenantId),
        chatsCount: chats.length,
        storeStats: instance.connection.getStoreStats?.(normalizedTenantId) || null
      });
      const filteredChats = chats.filter(chat => {
        const rawId = chat?.id?.id || chat?.id || chat?.jid || chat?.remoteJid || chat?.key?.remoteJid;
        if (!rawId) return false;
        const chatId = typeof rawId === 'string' ? rawId : String(rawId);
        return Boolean(chatId) && chatId.includes('@');
      });
 
      return filteredChats.map(chat => {
        const rawId = chat?.id?.id || chat?.id || chat?.jid || chat?.remoteJid || chat?.key?.remoteJid || '';
        const chatId = typeof rawId === 'string' ? rawId : String(rawId);
        const displayName = chat?.name || chat?.pushName || chat?.subject || (chatId ? chatId.split('@')[0] : 'Unknown');
        const phone = chatId ? chatId.split('@')[0] : '';
        const lastMessageText = chat?.lastMessage?.message?.conversation
          || chat?.lastMessage?.message?.extendedTextMessage?.text
          || chat?.lastMessage?.message?.imageMessage?.caption
          || chat?.lastMessage?.message?.videoMessage?.caption
          || '';
        const lastTimestamp = chat?.lastMessage?.messageTimestamp
          ? chat.lastMessage.messageTimestamp * 1000
          : (chat?.conversationTimestamp ? chat.conversationTimestamp * 1000 : 0);
 
        return {
          id: chatId,
          name: displayName,
          phone,
          avatar: null,
          lastMessage: lastMessageText,
          timestamp: lastTimestamp,
          stageId: 'new',
          tags: [],
          unreadCount: chat?.unreadCount || 0,
          conversationId: chatId,
          source: 'whatsapp_web'
        };
      });
    } catch (error) {
      logger.error('Error fetching Web WhatsApp conversations for tenant', {
        tenantId,
        error: error.message
      });
      return [];
    }
  }
 
  async forceWebSync(tenantId) {
    const normalizedTenantId = Number(tenantId);
    logger.info('Force web sync start', { tenantId: normalizedTenantId });
    let instance = this.getInstance(normalizedTenantId);
    if (!instance) {
      await this.initializeTenant(normalizedTenantId);
      instance = this.getInstance(normalizedTenantId);
    }
    if (!instance) return false;
    await instance.connection.forceHistorySync(normalizedTenantId);
    let chats = await instance.connection.getChats(normalizedTenantId);
    if (!chats.length) {
      await instance.connection.reconnect(normalizedTenantId);
      const waitFor = async (condition, timeoutMs, intervalMs) => {
        const start = Date.now();
        while (Date.now() - start < timeoutMs) {
          if (await condition()) return true;
          await new Promise(resolve => setTimeout(resolve, intervalMs));
        }
        return false;
      };
      await waitFor(() => instance.connection.isConnected(normalizedTenantId), 15000, 500);
      await waitFor(async () => {
        const nextChats = await instance.connection.getChats(normalizedTenantId);
        if (nextChats.length) {
          chats = nextChats;
          return true;
        }
        return false;
      }, 20000, 1000);
    }
    logger.info('Force web sync result', {
      tenantId: normalizedTenantId,
      connected: instance.connection.isConnected(normalizedTenantId),
      chatsCount: chats.length,
      storeStats: instance.connection.getStoreStats?.(normalizedTenantId) || null
    });
    return true;
  }
 
  /**
   * Disconnect WhatsApp for a tenant
   * @param {number} tenantId - Tenant ID
   * @returns {Promise<boolean>} Success status
   */
  async disconnect(tenantId) {
    try {
      const instance = this.getInstance(tenantId);
      
      if (!instance) {
        return false;
      }
 
      await instance.connection.disconnect(tenantId);
      
      // Remove instance
      this.tenantInstances.delete(tenantId);
      
      logger.info(`WhatsApp disconnected for tenant ${tenantId}`);
      
      return true;
    } catch (error) {
      logger.error(`Error disconnecting tenant ${tenantId}:`, error);
      return false;
    }
  }
 
  /**
   * Reconnect WhatsApp for a tenant
   * @param {number} tenantId - Tenant ID
   * @returns {Promise<boolean>} Success status
   */
  async reconnect(tenantId) {
    try {
      const instance = this.getInstance(tenantId);
      
      if (!instance) {
        // Initialize if not exists
        await this.initializeTenant(tenantId);
        return true;
      }
 
      await instance.connection.reconnect(tenantId);
      
      logger.info(`WhatsApp reconnection initiated for tenant ${tenantId}`);
      
      return true;
    } catch (error) {
      logger.error(`Error reconnecting tenant ${tenantId}:`, error);
      return false;
    }
  }
 
  /**
   * Clear session for a tenant
   * @param {number} tenantId - Tenant ID
   * @returns {Promise<boolean>} Success status
   */
  async clearSession(tenantId) {
    try {
      logger.info(`Clearing session for tenant ${tenantId}`);
      
      const instance = this.getInstance(tenantId);
      
      if (!instance) {
        logger.warn(`No instance found for tenant ${tenantId}`);
        return false;
      }
 
      // Disconnect first
      await instance.connection.disconnect(tenantId);
      
      // Backup before clearing
      instance.stateManager.backupSession(tenantId);
      
      // Clear session files
      const cleared = instance.stateManager.clearSession(tenantId);
      
      if (cleared) {
        instance.qrHandler.resetCounter(tenantId);
        instance.qrHandler.clearQR(tenantId);
        
        // Remove instance from map to force recreation
        this.tenantInstances.delete(tenantId);
        
        logger.info(`Session cleared and instance removed for tenant ${tenantId}`);
        return true;
      }
      
      return false;
    } catch (error) {
      logger.error(`Error clearing session for tenant ${tenantId}:`, error);
      return false;
    }
  }
 
  /**
   * Get QR code for a tenant
   * @param {number} tenantId - Tenant ID
   * @returns {string|null} QR code
   */
  getQRCode(tenantId) {
    const instance = this.getInstance(tenantId);
    return instance ? instance.qrHandler.getCurrentQR(tenantId) : null;
  }
 
  /**
   * Get all active tenant instances
   * @returns {Array} List of active tenants
   */
  getActiveTenants() {
    return Array.from(this.tenantInstances.keys());
  }
 
  /**
   * Disconnect all tenants (for shutdown)
   * @returns {Promise<void>}
   */
  async disconnectAll() {
    logger.info('Disconnecting all tenant WhatsApp instances');
    
    const disconnectPromises = Array.from(this.tenantInstances.keys()).map(
      tenantId => this.disconnect(tenantId)
    );
    
    await Promise.all(disconnectPromises);
    
    logger.info('All tenant instances disconnected');
  }
 
  /**
   * Clean old media for a tenant
   * @param {number} tenantId - Tenant ID
   * @param {number} daysToKeep - Days to keep media
   * @returns {Promise<number>} Number of files cleaned
   */
  async cleanOldMedia(tenantId, daysToKeep = 30) {
    try {
      const instance = this.getInstance(tenantId);
      
      if (!instance) {
        return 0;
      }
 
      const cleaned = instance.mediaHandler.cleanOldMedia(daysToKeep);
      logger.info(`Old media cleaned for tenant ${tenantId}:`, { cleaned });
      
      return cleaned;
    } catch (error) {
      logger.error(`Error cleaning media for tenant ${tenantId}:`, error);
      return 0;
    }
  }
 
  /**
   * Clean old backups for a tenant
   * @param {number} tenantId - Tenant ID
   * @param {number} daysToKeep - Days to keep backups
   * @returns {Promise<number>} Number of backups cleaned
   */
  async cleanOldBackups(tenantId, daysToKeep = 7) {
    try {
      const instance = this.getInstance(tenantId);
      
      if (!instance) {
        return 0;
      }
 
      const cleaned = instance.stateManager.cleanOldBackups(daysToKeep);
      logger.info(`Old backups cleaned for tenant ${tenantId}:`, { cleaned });
      
      return cleaned;
    } catch (error) {
      logger.error(`Error cleaning backups for tenant ${tenantId}:`, error);
      return 0;
    }
  }
 
  /**
   * Get tenant status (wrapper for Controller)
   * @param {number} tenantId - Tenant ID
   * @returns {Promise<Object>} Status object
   */
  async getTenantStatus(tenantId) {
    try {
      logger.info('Getting tenant status', { tenantId });
      
      const status = this.getStatus(tenantId);
      logger.info('Status retrieved', { tenantId, status });
      
      // Get QR code if connecting
      let qrCode = null;
      const instance = this.getInstance(tenantId);
      
      if (instance && instance.qrHandler) {
        qrCode = instance.qrHandler.getCurrentQR(tenantId);
        logger.info('QR code retrieved from handler', { 
          tenantId, 
          hasQR: !!qrCode,
          qrLength: qrCode ? qrCode.length : 0,
          qrPreview: qrCode ? qrCode.substring(0, 50) + '...' : null
        });
      } else {
        logger.warn('No instance or qrHandler found', { 
          tenantId,
          hasInstance: !!instance,
          hasQRHandler: instance ? !!instance.qrHandler : false
        });
      }
 
      const result = {
        status: status.connected ? 'connected' : (status.initialized ? 'connecting' : 'disconnected'),
        phoneNumber: status.phoneNumber,
        qr: qrCode,
        ...status
      };
      
      logger.info('Returning tenant status', { 
        tenantId, 
        statusValue: result.status,
        hasQR: !!result.qr,
        qrLength: result.qr ? result.qr.length : 0,
        connected: status.connected,
        initialized: status.initialized
      });
      
      return result;
    } catch (error) {
      logger.error(`Error getting tenant status: ${error.message}`, { tenantId, stack: error.stack });
      return {
        status: 'disconnected',
        error: error.message
      };
    }
  }
 
  /**
   * Get current QR code for tenant
   * @param {number} tenantId - Tenant ID
   * @returns {Promise<string|null>} QR code data URL
   */
  async getQRCode(tenantId) {
    try {
      const instance = this.getInstance(tenantId);
      
      if (!instance || !instance.qrHandler) {
        return null;
      }
 
      return instance.qrHandler.getCurrentQR(tenantId);
    } catch (error) {
      logger.error(`Error getting QR code: ${error.message}`, { tenantId });
      return null;
    }
  }
 
  /**
   * Disconnect tenant (wrapper for Controller)
   * @param {number} tenantId - Tenant ID
   * @returns {Promise<boolean>} Success status
   */
  async disconnectTenant(tenantId) {
    return await this.disconnect(tenantId);
  }
 
  /**
   * Clear tenant session (wrapper for Controller)
   * @param {number} tenantId - Tenant ID
   * @returns {Promise<boolean>} Success status
   */
  async clearTenantSession(tenantId) {
    return await this.clearSession(tenantId);
  }
 
  /**
   * Get messages for tenant
   * @param {number} tenantId - Tenant ID
   * @param {Object} options - Query options
   * @returns {Promise<Object>} Messages data
   */
  async getMessages(tenantId, options = {}) {
    try {
      const { limit = 50, offset = 0, phoneNumber } = options;
      
      const WhatsAppMessage = require('../models/WhatsAppMessage');
      
      let query = `
        SELECT * FROM whatsapp_messages 
        WHERE tenant_id = ?
      `;
      const params = [tenantId];
 
      if (phoneNumber) {
        query += ` AND phone_number = ?`;
        params.push(phoneNumber);
      }
 
      query += ` ORDER BY created_at DESC LIMIT ? OFFSET ?`;
      params.push(limit, offset);
 
      const [messages] = await pool.query(query, params);
 
      return {
        messages,
        total: messages.length,
        limit,
        offset
      };
    } catch (error) {
      logger.error(`Error getting messages: ${error.message}`, { tenantId });
      throw error;
    }
  }
 
  /**
   * Get contacts for tenant
   * @param {number} tenantId - Tenant ID
   * @param {Object} options - Query options
   * @returns {Promise<Object>} Contacts data
   */
  async getContacts(tenantId, options = {}) {
    try {
      const { limit = 50, offset = 0, search } = options;
      
      const WhatsAppContact = require('../models/WhatsAppContact');
      
      let query = `
        SELECT * FROM whatsapp_contacts 
        WHERE tenant_id = ?
      `;
      const params = [tenantId];
 
      if (search) {
        query += ` AND (name LIKE ? OR phone_number LIKE ?)`;
        params.push(`%${search}%`, `%${search}%`);
      }
 
      query += ` ORDER BY last_message_at DESC LIMIT ? OFFSET ?`;
      params.push(limit, offset);
 
      const [contacts] = await pool.query(query, params);
 
      return {
        contacts,
        total: contacts.length,
        limit,
        offset
      };
    } catch (error) {
      logger.error(`Error getting contacts: ${error.message}`, { tenantId });
      throw error;
    }
  }
 
  /**
   * Restore all saved sessions on server startup
   * @returns {Promise<void>}
   */
  async restoreAllSessions() {
    try {
      logger.info('🔄 Restoring saved WhatsApp sessions...');
      
      // Get all active tenants (exclude system tenant id=0)
      const [tenants] = await pool.query(
        `SELECT id, name FROM tenants WHERE status = 'active' AND id != 0`
      );
      
      logger.info(`Found ${tenants.length} active tenants`);
      
      let restored = 0;
      let skipped = 0;
      
      for (const tenant of tenants) {
        try {
          // Check if tenant has saved session
          const sessionPath = path.join(this.sessionsPath, `tenant_${tenant.id}`, 'creds.json');
          const hasSession = await fs.access(sessionPath).then(() => true).catch(() => false);
          
          if (hasSession) {
            logger.info(`📁 Restoring session for tenant: ${tenant.name} (ID: ${tenant.id})`);
            
            // Initialize connection (will load saved session)
            await this.initializeTenant(tenant.id);
            restored++;
            
            // Small delay to avoid overwhelming the system
            await new Promise(resolve => setTimeout(resolve, 2000));
          } else {
            logger.debug(`⏭️  No saved session for tenant: ${tenant.name} (ID: ${tenant.id})`);
            skipped++;
          }
        } catch (error) {
          logger.error(`❌ Failed to restore session for tenant ${tenant.id}:`, error.message);
        }
      }
      
      logger.info(`✅ Session restoration complete: ${restored} restored, ${skipped} skipped`);
    } catch (error) {
      logger.error('Error restoring sessions:', error);
    }
  }
}
 
// Singleton instance
let whatsappServiceInstance = null;
 
/**
 * Get WhatsApp service instance
 * @param {Object} io - Socket.IO instance
 * @returns {WhatsAppService} Service instance
 */
function getWhatsAppService(io) {
  if (!whatsappServiceInstance && io) {
    whatsappServiceInstance = new WhatsAppService(io);
  }
  return whatsappServiceInstance;
}
 
module.exports = { WhatsAppService, getWhatsAppService };